package com.zzzs.forkjoin;

import java.util.concurrent.ForkJoinPool;
import java.util.stream.LongStream;

/**
 * @author zhu_shuai
 * @since 2021/6/28
 */
public class DemoTest {
    private static Long endNum = 10_0000_0000L;
    public static void main(String[] args) {
        System.out.println(Runtime.getRuntime().availableProcessors() + "核");
        test1();
        test2();
        test3();
    }

    /**
     * 循环累加
     */
    private static void test1(){
        long sum = 0;
        long l = System.currentTimeMillis();
        for (int i = 0; i < endNum; i++) {
            sum += i;
        }
        System.out.println(sum);
        long end = System.currentTimeMillis();
        System.out.println(end-l);
    }

    /**
     * 分而治之
     */
    private static void test2(){
        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinDemo task = new ForkJoinDemo(0L, endNum);
        forkJoinPool.submit(task);
        Long join = task.join();
        long end = System.currentTimeMillis();
        System.out.println(join);
        System.out.println(end-start);
    }

    /**
     * stream流
     */
    private static void test3(){
        long l = System.currentTimeMillis();

        long sum = LongStream.range(0L, endNum).parallel().sum();
        System.out.println(sum);
        long end = System.currentTimeMillis();
        System.out.println(end-l);
    }
}
